package com.credithc.signature.core.util;

import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.OperationContext;
import com.microsoft.azure.storage.blob.BlobContainerPublicAccessType;
import com.microsoft.azure.storage.blob.BlobRequestOptions;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
import com.microsoft.azure.storage.blob.CloudBlockBlob;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;

/**
 * 描述：微软云上传util<br/>
 * 作者：sunyang
 * 创建：2019/6/4 16:39
 * 版本：v1.0.0<br/>
 */
@Slf4j
public class AzureUtil {

    public static String uploadFile(InputStream is, String fileName, String accountName, String accountKey,
                                    String endpoitSuffit, String containerName) throws Exception {

        CloudBlockBlob blob = buildBlob(fileName, accountName, accountKey, endpoitSuffit, containerName);

        try {
            blob.upload(is, is.available());
            return fileName;
        } catch (Exception e) {
            log.error("上传微软云失败", e);
            throw new RuntimeException(e);
        }
    }

    private static CloudBlockBlob buildBlob(String fileName, String accountName, String accountKey,
                                            String endpoitSuffit, String containerName) throws Exception {

        String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="+ accountName +";AccountKey="
                + accountKey +";EndpointSuffix=" + endpoitSuffit;

        CloudStorageAccount storageAccount;
        CloudBlobClient blobClient = null;
        CloudBlobContainer container = null;
        try {
            storageAccount = CloudStorageAccount.parse(storageConnectionString);
            blobClient = storageAccount.createCloudBlobClient();
            container = blobClient.getContainerReference(containerName);

            container.createIfNotExists(BlobContainerPublicAccessType.CONTAINER, new BlobRequestOptions(), new OperationContext());

            return container.getBlockBlobReference(fileName);
        } catch (Exception e) {
            log.error("上传微软云失败", e);
            throw new RuntimeException(e);
        }
    }

    public static byte[] downloadFile(String fileName, String accountName, String accountKey,
                                      String endpoitSuffit, String containerName) throws Exception {

        CloudBlockBlob blob = buildBlob(fileName, accountName, accountKey, endpoitSuffit, containerName);

        try {
            int readTotal = 0;
            byte[] dataBuffer = new byte[2048];
            byte[] buffer = new byte[1024];
            int readLength = blob.downloadToByteArray(buffer, 0);
            int maxTotalLoop = 10000000;
            int currentTotalLoop = 0;
            while (readLength != -1){
                currentTotalLoop++;
                if (readLength + readTotal > dataBuffer.length) {
                    dataBuffer = ByteUtil.grow(dataBuffer, 2048);
                }
                System.arraycopy(buffer,0,dataBuffer,0,readLength);
                readTotal += readLength;
                if (currentTotalLoop >= maxTotalLoop) {
                    throw new Exception("循环读取次数超限,最大读取次数为:" + maxTotalLoop);
                }
            }
            byte[] data = new byte[readTotal];
            System.arraycopy(dataBuffer,0,data,0,readTotal);
            return data;
        } catch (Exception e) {
            log.error("上传微软云失败", e);
            throw new RuntimeException(e);
        }

    }
}

